Binary Tree Level Order Traversal (easy)
We'll cover the following
Problem Statement #
Given a binary tree, populate an array to represent its level-by-level traversal. You should populate the values of all nodes of each level from left to right in separate sub-arrays.
Example 1:
Example 2:
Try it yourself #
Try solving this question here:
Solution #
Since we need to traverse all nodes of each level before moving onto the next level, we can use the Breadth First Search (BFS) technique to solve this problem.
We can use a Queue to efficiently traverse in BFS fashion. Here are the steps of our algorithm:
- Start by pushing the
root
node to the queue. - Keep iterating until the queue is empty.
- In each iteration, first count the elements in the queue (letās call it
levelSize
). We will have these many nodes in the current level. - Next, remove
levelSize
nodes from the queue and push theirvalue
in an array to represent the current level. - After removing each node from the queue, insert both of its children into the queue.
- If the queue is not empty, repeat from step 3 for the next level.
Letās take the example-2 mentioned above to visually represent our algorithm:
Code #
Here is what our algorithm will look like:
Time complexity #
The time complexity of the above algorithm is , where āNā is the total number of nodes in the tree. This is due to the fact that we traverse each node once.
Space complexity #
The space complexity of the above algorithm will be as we need to return a list containing the level order traversal. We will also need space for the queue. Since we can have a maximum of nodes at any level (this could happen only at the lowest level), therefore we will need space to store them in the queue.